import { createFileRoute } from '@tanstack/react-router'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { 
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Edit, Save, X } from 'lucide-react'
import { useState, useEffect } from 'react'
import { toast } from 'sonner'

export const Route = createFileRoute('/seals/')({
  component: SealsPage,
})

// 配置项数据类型
interface ConfigItem {
  id: number;
  name: string;
  description: string;
  value: string;
}

interface ApiResponse {
  code: number;
  msg: string;
  data: ConfigItem[];
}

// 获取配置列表API
const fetchConfigs = async (): Promise<ApiResponse> => {
  const token = localStorage.getItem('auth_token');
  
  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  const response = await fetch('/huibanhao/seal/config', {
    headers: {
      'Authorization': token,
      'Accept': 'application/json',
    },
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`请求失败: ${response.status}`);
  }

  return response.json();
};

// 更新配置API
const updateConfig = async (id: number, value: string): Promise<{code: number; msg: string}> => {
  const token = localStorage.getItem('auth_token');
  
  if (!token) {
    throw new Error('未找到认证token，请重新登录');
  }

  const response = await fetch('/huibanhao/seal/config', {
    method: 'POST',
    headers: {
      'Authorization': token,
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ id, value }),
  });

  if (!response.ok) {
    if (response.status === 401) {
      throw new Error('认证失败，请重新登录');
    }
    throw new Error(`请求失败: ${response.status}`);
  }

  return response.json();
};

function SealsPage() {
  const [configs, setConfigs] = useState<ConfigItem[]>([])
  const [loading, setLoading] = useState(false)
  const [editingId, setEditingId] = useState<number | null>(null)
  const [editValue, setEditValue] = useState('')
  const [updateLoading, setUpdateLoading] = useState<{[key: number]: boolean}>({})

  // 加载配置数据
  const loadConfigs = async () => {
    setLoading(true);
    try {
      const response = await fetchConfigs();
      if (response.code === 200) {
        setConfigs(response.data);
      } else {
        toast.error(response.msg || '获取配置数据失败');
        setConfigs([]);
      }
    } catch (error) {
      console.error('Failed to load configs:', error);
      const errorMessage = error instanceof Error ? error.message : '获取配置数据失败';
      toast.error(errorMessage);
      setConfigs([]);
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    loadConfigs();
  }, []);

  // 开始编辑
  const startEdit = (config: ConfigItem) => {
    setEditingId(config.id);
    setEditValue(config.value);
  };

  // 取消编辑
  const cancelEdit = () => {
    setEditingId(null);
    setEditValue('');
  };

  // 保存编辑
  const saveEdit = async (id: number) => {
    if (!editValue.trim()) {
      toast.error('配置值不能为空');
      return;
    }

    setUpdateLoading(prev => ({ ...prev, [id]: true }));
    try {
      const result = await updateConfig(id, editValue.trim());
      if (result.code === 200) {
        // 更新本地状态
        setConfigs(prev => prev.map(config => 
          config.id === id ? { ...config, value: editValue.trim() } : config
        ));
        setEditingId(null);
        setEditValue('');
        toast.success('配置更新成功');
      } else {
        toast.error(result.msg || '配置更新失败');
      }
    } catch (error) {
      console.error('Update config failed:', error);
      const errorMessage = error instanceof Error ? error.message : '配置更新失败';
      toast.error(errorMessage);
    } finally {
      setUpdateLoading(prev => ({ ...prev, [id]: false }));
    }
  };

  // 渲染配置值（特殊处理二维码图片）
  const renderConfigValue = (config: ConfigItem) => {
    if (config.name === 'qrcode' && config.value.startsWith('http')) {
      return (
        <div className="flex items-center space-x-2">
          <img 
            src={config.value} 
            alt="企业客服二维码" 
            className="w-12 h-12 object-cover rounded border"
          />
          <div className="text-sm text-gray-500">
            {config.value.split('/').pop()}
          </div>
        </div>
      );
    }
    return <div className="text-sm">{config.value}</div>;
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">在线刻章-刻章配置</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          管理刻章服务的基础配置信息
        </p>
      </div>

      {/* 配置列表 */}
      <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="text-gray-500">加载中...</div>
            </div>
          ) : (
            <div className="border rounded-lg">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>配置名称</TableHead>
                    <TableHead>配置描述</TableHead>
                    <TableHead>配置值</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {configs.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={4} className="text-center py-8 text-gray-500">
                        暂无配置数据
                      </TableCell>
                    </TableRow>
                  ) : (
                    configs.map((config) => (
                      <TableRow key={config.id}>
                        <TableCell>
                          <div className="font-medium">{config.name}</div>
                        </TableCell>
                        <TableCell>
                          <div className="text-sm text-gray-600">{config.description}</div>
                        </TableCell>
                        <TableCell>
                          {editingId === config.id ? (
                            <div className="flex items-center space-x-2">
                              <Input
                                value={editValue}
                                onChange={(e) => setEditValue(e.target.value)}
                                className="flex-1"
                                placeholder="请输入配置值"
                                disabled={updateLoading[config.id]}
                              />
                            </div>
                          ) : (
                            renderConfigValue(config)
                          )}
                        </TableCell>
                        <TableCell className="text-right">
                          {editingId === config.id ? (
                            <div className="flex items-center justify-end space-x-2">
                              <Button
                                size="sm"
                                onClick={() => saveEdit(config.id)}
                                disabled={updateLoading[config.id]}
                                className="h-8 px-2"
                              >
                                <Save className="h-3 w-3" />
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={cancelEdit}
                                disabled={updateLoading[config.id]}
                                className="h-8 px-2"
                              >
                                <X className="h-3 w-3" />
                              </Button>
                            </div>
                          ) : (
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => startEdit(config)}
                              className="h-8 px-2"
                            >
                              <Edit className="h-3 w-3" />
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
    </div>
  )
}
